package com.fjwt.gz.task.oldScore;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.support.geo.Geometry;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.dto.InviterRecordDTO;
import com.fjwt.gz.db.entity.AgentScoreRuleEntity;
import com.fjwt.gz.db.entity.FansUserEntity;
import com.fjwt.gz.db.entity.InviterRecordEntity;
import com.fjwt.gz.service.impl.AgentScoreRuleService;
import com.fjwt.gz.service.impl.FansUserService;
import com.fjwt.gz.service.impl.InviterRecordService;
import com.fjwt.gz.service.impl.ScoreRecordTotalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 邀请新用户送福分
 */

@Slf4j
@Component
public class InviterScoreTask {
    @Autowired
    private InviterRecordService inviterRecordService;

    @Autowired
    private AgentScoreRuleService agentScoreRuleService;

    @Autowired
    private FansUserService fansUserService;

    @Autowired
    private ScoreRecordTotalService scoreRecordTotalService;

    private static final int QUERY_PAGE_SIZE = 1000; //每次查询数量

//    @Scheduled(cron = "${cron.InviterScoreTask}")//每3秒执行一次
    @Transactional
    public void start() {
        log.info("开始进入邀请新用户送福分，开始时间:{}", DateUtil.now());
        int currentPageIndex = 1; //当前页码
        LambdaQueryWrapper<AgentScoreRuleEntity> queryWrapperRule = new LambdaQueryWrapper<>();
        queryWrapperRule.eq(AgentScoreRuleEntity::getRuleKey, Constants.POINT.INVITER_KEY);
        queryWrapperRule.eq(AgentScoreRuleEntity::getState, 1);
        List<AgentScoreRuleEntity> ruleList = agentScoreRuleService.getBaseMapper().selectList(queryWrapperRule);
        if (CollUtil.isEmpty(ruleList) || ruleList.size() > 1) {
            return;
        }
        while (true) {
            try {
                IPage<InviterRecordDTO> recordPage = inviterRecordService.queryInviterRecord(new Page(currentPageIndex, QUERY_PAGE_SIZE));
                log.info("查询页数：{}，size:{}，结果list：{}", currentPageIndex, QUERY_PAGE_SIZE, JSONUtil.toJsonStr(recordPage));
                if (recordPage == null || CollUtil.isEmpty(recordPage.getRecords())) { //本次查询无结果, 不再继续查询;
                    break;
                }
                List<InviterRecordDTO> records = recordPage.getRecords();
                for (InviterRecordDTO a : records) {
                    if (null == a.getFansId() || StringUtils.isEmpty(a.getOpenId()) || StringUtils.isEmpty(a.getAppId()) || StringUtils.isEmpty(a.getPhone())) {
                        continue;
                    }
                    FansUserEntity userEntity = fansUserService.selectFansByOpenIdAndAppid("0", a.getOpenId(), a.getOfficialAppId());
                    if (null == userEntity) {
                        continue;
                    }
                    if (0 == userEntity.getIsFollow()) {
                        int generate = scoreRecordTotalService.scoreRecordGenerate(a.getFansId(), ruleList.get(0).getScoreRuleId(), "邀请新人获得福分", Constants.SCORE.RULE, null, a.getAppId());
                        if (generate > 0) {
                            a.setIsFollow(1);
                            a.setIsSuccess(1);
                            InviterRecordEntity inviterRecordEntity = new InviterRecordEntity();
                            BeanUtils.copyProperties(a, inviterRecordEntity);
                            inviterRecordService.updateById(inviterRecordEntity);
                        }
                    }
                }
                currentPageIndex = currentPageIndex + 1;
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
        log.info("结束用户历史积分数据迁移，结束时间:{}", DateUtil.now());
    }
}
